<?php

// MySQL-Based Session
// Create by Hoang Dinh Tien
//
include_once("config.php");
	/*
	 * msql_session_open()
	 */
	 function mysql_session_open($session_path, $session_name) {
		db_connection();
	 }
	 
	 /*
	  * mysql_session_close()
	  */
	 function mysql_session_close() {
		return 1;
	 }
	 
	 /*
	  * mysql_session_select()
	  */
	 function mysql_session_select() {
		$query = "SELECT value FROM sessioninfo where SID = '$SID' AND expiration > ".time();
		$result = mysql_query($query);
		
		if (mysql_num_rows($result)) {
			$row = mysql_fetch_assoc($result);
			$value = $row['value'];
			return $value;
		}
		else {
			return "";
		}
	 }
	 
	 
	 /*
	  * mysql_session_write()
	  */
	 function mysql_session_write($SID, $value) {
		$lifetime = get_cfg_var("session.gc_maxlifetime");
		$expiration = time() + $lifetime;
		
		//Insert to DB
		$query = "INSERT INTO sessioninfo VALUES ('$SID','$expiration','$value')";
		
		$result = mysql_query ($query);
		
		//If fail the session already in DB
		//Therefore update instead
		
		if (!$result) {
			$query = "UPDATE sessioninfo SET expiration = '$expiration', valure = '$value' WHERE SID = '$SID' AND expiration >".time();
			
			$result = mysql_query ($query);
		}
	 }
	 
	 /*
	  * mysql_session_destroy()
	  */
	 function mysql_session_destroy($SID) {
		$query = "DELETE FROM sessioninfo WHERE SID = '$SID'";
			
		$result = mysql_query ($query);
	 }
	 
	 /*
	  * mysql_session_garbage_collect()
	  */
	 function mysql_session_garbage_collect($lifetime) {
		$query = "DELETE FROM sessioninfo WHERE expiration <".time() - $lifetime;
		
		$result = mysql_query ($query);
		return mysql_affected_rows($result);
	  }
	  
	 session_set_save_handler ("mysql_session_open","mysql_session_close","mysql_session_select","mysql_session_write","mysql_session_destroy","mysql_session_garbage_collect");
?>